
package com.afd.ozblip.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.afd.ozblip.adapter.VipListAdapter;
import com.afd.ozblip.entity.CategoryEntity;
import com.afd.ozblip.entity.VipEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.CollectionUtil;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.OzblipConfig;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.view.UIPullRefereshListView;
import com.afd.ozblip.view.UIPullRefereshListView.OnFooterLoadListener;
import com.afd.ozblip.view.UIPullRefereshListView.OnRefreshListener;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class NearbyVipActivity extends BaseActivity {

    /****************** 视图变量 **************************/
    private LinearLayout activityLayout;
    private UIPullRefereshListView vipListView;

    private LinearLayout areaFilterLayout;
    private LinearLayout conAreaLayout;
    private LinearLayout categoryFilterLayout;
    private RadioGroup categoryFilterLeftLayout;
    private FrameLayout categoryFilterRightLayout;
    private LinearLayout conCategoryLayout;
    private LinearLayout sortFilterLayout;
    private LinearLayout conSortLayout;
    // 排序视图
    private LinearLayout sort0Layout;
    private LinearLayout sort1Layout;
    private LinearLayout sort2Layout;
    private LinearLayout sort3Layout;
    private LinearLayout sort4Layout;

    private TextView areaTv;
    private TextView categoryTv;
    private TextView sortTv;
    private TextView dataTipTv;
    protected Animation animPushTopIn;
    protected Animation animPushTopOut;

    private ListView areaListView;
    /****************** 数据条件变量 ***********************/
    // 父级类型名称
    private String parentClassName = "";
    // 子级类型名称
    private String childClassName = "";
    // 区域编号
    private String areaId = "";
    // 排序方式
    private int sortVal = 0;
    /****************** 其它变量 **************************/
    private List<VipEntity> nbVipList;
    private VipListAdapter nbVipListAdapter;
    // 当前页码
    private int nowPage = 1;
    // 总页数
    private int totalPage = 1;
    // 总分类长度
    private int classLen;
    private int parentClassIndex;
    private List<CategoryEntity> categoryList;
    // 活动公告
    private StringBuffer activityNoticeStr;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nearby_business_vip);
        // 启动返回功能
        toBack();
        // 寻找视图
        findViews();
        // 设置监听
        setListeners();
        // 获取参数
        getBundle();
        // 获取列表数据
        requestAreaListData();
        this.vipListView.referesh();

    }

    /**
     * 寻找视图
     */
    public void findViews() {
        this.activityLayout = (LinearLayout) findViewById(R.id.ll_vip_activity);
        this.vipListView = (UIPullRefereshListView) findViewById(R.id.lv_search_vipList);
        this.areaListView = (ListView) findViewById(R.id.lv_area_list);
        // 条件选择视图
        this.dataTipTv = (TextView) findViewById(R.id.tv_list_data_tip);
        this.areaTv = (TextView) findViewById(R.id.tv_conditon_area);
        this.categoryTv = (TextView) findViewById(R.id.tv_conditon_category);
        this.sortTv = (TextView) findViewById(R.id.tv_conditon_sort);
        this.areaFilterLayout = (LinearLayout) findViewById(R.id.ll_conditon_filter_area);
        this.conAreaLayout = (LinearLayout) findViewById(R.id.ll_conditon_area);
        this.categoryFilterLayout = (LinearLayout) findViewById(R.id.ll_conditon_filter_category);
        this.conCategoryLayout = (LinearLayout) findViewById(R.id.ll_conditon_category);
        this.sortFilterLayout = (LinearLayout) findViewById(R.id.ll_conditon_filter_sort);
        this.conSortLayout = (LinearLayout) findViewById(R.id.ll_conditon_sort);
        this.animPushTopIn = AnimationUtils.loadAnimation(this,
                R.anim.push_top_in);
        this.animPushTopOut = AnimationUtils.loadAnimation(this,
                R.anim.push_top_out);
        // 排序选择视图
        this.sort0Layout = (LinearLayout) findViewById(R.id.ll_condition_sort0);
        this.sort1Layout = (LinearLayout) findViewById(R.id.ll_condition_sort1);
        this.sort2Layout = (LinearLayout) findViewById(R.id.ll_condition_sort2);
        this.sort3Layout = (LinearLayout) findViewById(R.id.ll_condition_sort3);
        this.sort4Layout = (LinearLayout) findViewById(R.id.ll_condition_sort4);
        // 初始化分类
        initCategory();
        // 初始化活动公告
        activityNoticeStr = new StringBuffer();
    }

    /**
     * 设置监听
     */
    public void setListeners() {

        View.OnClickListener vipClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_vip_activity:
                        Intent settingIntent = new Intent(NearbyVipActivity.this,
                                VipActivityNoticeListActivity.class);
                        settingIntent.putExtra("activityNoticeStr",
                                activityNoticeStr.toString());
                        startActivity(settingIntent);
                        break;
                    case R.id.ll_conditon_area:
                        categoryFilterLayout.setVisibility(8);
                        sortFilterLayout.setVisibility(8);
                        conAreaLayout.setBackgroundColor(getResources().getColor(
                                R.color.condition_select_bg));
                        conCategoryLayout.setBackgroundColor(getResources()
                                .getColor(R.color.transparent));
                        conSortLayout.setBackgroundColor(getResources().getColor(
                                R.color.transparent));
                        if (areaFilterLayout.getVisibility() == 8) {
                            showFilter(areaFilterLayout);
                        } else {
                            hideFilter(areaFilterLayout);
                        }
                        break;
                    case R.id.ll_conditon_category:
                        areaFilterLayout.setVisibility(8);
                        sortFilterLayout.setVisibility(8);
                        conAreaLayout.setBackgroundColor(getResources().getColor(
                                R.color.transparent));
                        conCategoryLayout.setBackgroundColor(getResources()
                                .getColor(R.color.condition_select_bg));
                        conSortLayout.setBackgroundColor(getResources().getColor(
                                R.color.transparent));
                        if (categoryFilterLayout.getVisibility() == 8) {
                            showFilter(categoryFilterLayout);
                        } else {
                            hideFilter(categoryFilterLayout);
                        }
                        break;
                    case R.id.ll_conditon_sort:
                        areaFilterLayout.setVisibility(8);
                        categoryFilterLayout.setVisibility(8);
                        conAreaLayout.setBackgroundColor(getResources().getColor(
                                R.color.transparent));
                        conCategoryLayout.setBackgroundColor(getResources()
                                .getColor(R.color.transparent));
                        conSortLayout.setBackgroundColor(getResources().getColor(
                                R.color.condition_select_bg));
                        if (sortFilterLayout.getVisibility() == 8) {
                            showFilter(sortFilterLayout);
                        } else {
                            hideFilter(sortFilterLayout);
                        }
                        break;
                    case R.id.ll_condition_sort0:
                    case R.id.ll_condition_sort1:
                    case R.id.ll_condition_sort2:
                    case R.id.ll_condition_sort3:
                    case R.id.ll_condition_sort4:
                        sortVal = Integer.valueOf(v.getTag().toString()) + 1;
                        conSortLayout.setBackgroundColor(getResources().getColor(
                                R.color.transparent));
                        if (sortFilterLayout.getVisibility() == 8) {
                            showFilter(sortFilterLayout);
                        } else {
                            hideFilter(sortFilterLayout);
                        }
                        dataTipTv.setVisibility(8);
                        vipListView.referesh();
                        break;
                    default:
                        break;
                }
            }
        };
        this.activityLayout.setOnClickListener(vipClick);
        this.conAreaLayout.setOnClickListener(vipClick);
        this.conCategoryLayout.setOnClickListener(vipClick);
        // 排序选择事件
        this.conSortLayout.setOnClickListener(vipClick);
        this.sort0Layout.setOnClickListener(vipClick);
        this.sort1Layout.setOnClickListener(vipClick);
        this.sort2Layout.setOnClickListener(vipClick);
        this.sort3Layout.setOnClickListener(vipClick);
        this.sort4Layout.setOnClickListener(vipClick);
        this.nbVipListAdapter = new VipListAdapter(NearbyVipActivity.this);
        nbVipList = new ArrayList<VipEntity>();
        this.nbVipListAdapter.addItems(nbVipList);
        this.vipListView.setAdapter(this.nbVipListAdapter);
        this.vipListView.setonRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                nowPage = 1;
                requestVipListData(true);
            }
        });
        this.vipListView.setOnFooterLoadListener(new OnFooterLoadListener() {

            @Override
            public void onLoad() {
                if (nowPage < totalPage) {
                    requestVipListData(false);
                    nowPage = nowPage + 1;
                    vipListView.nowPage = nowPage;
                }
            }
        });
        this.vipListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> itemView, View arg1,
                    int parameInt, long arg3) {
                Intent businessIntent = new Intent(NearbyVipActivity.this,
                        VipDetailActivity.class);
                VipEntity vip = NearbyVipActivity.this.nbVipList
                        .get(parameInt - 1);
                businessIntent.putExtra("vipInfo", vip);
                startActivity(businessIntent);
            }
        });
    }

    private void showFilter(LinearLayout layout) {
        layout.setVisibility(0);
        layout.startAnimation(this.animPushTopIn);
    }

    private void hideFilter(LinearLayout layout) {
        layout.startAnimation(this.animPushTopOut);
        layout.setVisibility(8);
    }

    // TODO 初始化分类
    private void initCategory() {
        this.categoryFilterLeftLayout = (RadioGroup) findViewById(R.id.ll_conditon_filter_category_left);
        this.categoryFilterRightLayout = (FrameLayout) findViewById(R.id.ll_conditon_filter_category_right);

        LayoutInflater inflater = LayoutInflater.from(this);
        categoryList = Constants.getCategoryList();
        classLen = categoryList.size();
        View.OnClickListener leftClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int index = Integer.parseInt(v.getTag().toString());
                parentClassIndex = index;
                for (int i = 0, len = classLen; i < len; i++) {
                    categoryFilterRightLayout.getChildAt(i).setVisibility(8);
                }
                categoryFilterRightLayout.getChildAt(index).setVisibility(0);
            }
        };
        View.OnClickListener rightClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int index = Integer.parseInt(v.getTag().toString());
                parentClassName = categoryList.get(parentClassIndex)
                        .getParentClassName();
                childClassName = categoryList.get(parentClassIndex)
                        .getChildClassList().get(index);
                conCategoryLayout.setBackgroundColor(getResources().getColor(
                        R.color.transparent));
                if (categoryFilterLayout.getVisibility() == 8) {
                    showFilter(categoryFilterLayout);
                } else {
                    hideFilter(categoryFilterLayout);
                }
                categoryTv.setText(childClassName);
                vipListView.referesh();
            }
        };
        for (int i = 0, len = categoryList.size(); i < len; i++) {
            View leftView = inflater.inflate(R.layout.category_left_item, null);
            RadioButton leftRB = (RadioButton) leftView;
            String parentCN = categoryList.get(i).getParentClassName();
            leftRB.setText(parentCN);
            leftRB.setId(i);
            if ("热门分类".equals(parentCN)) {
                leftRB.setChecked(true);
            }
            // 设置drawableleft
            BitmapDrawable leftbd = getListIco(i);
            leftRB.setCompoundDrawablesWithIntrinsicBounds(leftbd, null, null,
                    null);
            // 设置tag
            leftRB.setTag(i);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            leftView.setOnClickListener(leftClick);
            this.categoryFilterLeftLayout.addView(leftView, lp);
            LinearLayout ll = new LinearLayout(this);
            ll.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT));
            ll.setOrientation(LinearLayout.VERTICAL);
            ll.setVisibility(i == 0 ? 0 : 8);
            List<String> childClassList = categoryList.get(i)
                    .getChildClassList();
            for (int j = 0, childLen = childClassList.size(); j < childLen; j++) {
                View rightView = inflater.inflate(R.layout.category_right_item,
                        null);
                rightView.setBackgroundResource(R.drawable.ll_bg_selector);
                rightView.setTag(j);
                rightView.setOnClickListener(rightClick);
                TextView rightTv = (TextView) rightView
                        .findViewById(R.id.tv_category_right);
                rightTv.setText(childClassList.get(j));

                ll.addView(rightView, lp);
            }
            this.categoryFilterRightLayout.addView(ll);
        }
    }

    private BitmapDrawable getListIco(int index) {
        Resources res = getResources();
        BitmapDrawable bd = null;
        Bitmap bm = null;
        switch (index) {
            case 0:
                bm = BitmapFactory.decodeResource(res, R.drawable.list_ico1);
                bd = new BitmapDrawable(res, bm);
                break;
            case 1:
                bm = BitmapFactory.decodeResource(res, R.drawable.list_ico2);
                bd = new BitmapDrawable(res, bm);
                break;
            case 2:
                bm = BitmapFactory.decodeResource(res, R.drawable.list_ico3);
                bd = new BitmapDrawable(res, bm);
                break;
            case 3:
                bm = BitmapFactory.decodeResource(res, R.drawable.list_ico4);
                bd = new BitmapDrawable(res, bm);
                break;
            case 4:
                bm = BitmapFactory.decodeResource(res, R.drawable.list_ico5);
                bd = new BitmapDrawable(res, bm);
                break;
            case 5:
                bm = BitmapFactory.decodeResource(res, R.drawable.list_ico6);
                bd = new BitmapDrawable(res, bm);
                break;
            case 6:
                bm = BitmapFactory.decodeResource(res, R.drawable.list_ico7);
                bd = new BitmapDrawable(res, bm);
                break;
            case 7:
                bm = BitmapFactory.decodeResource(res, R.drawable.list_ico8);
                bd = new BitmapDrawable(res, bm);
                break;

            default:
                break;
        }
        return bd;
    }

    /**
     * 获取传递的参数
     */
    private void getBundle() {
        Intent intent = getIntent();
    }

    /**
     * 获取区域列表数据
     */
    private void requestAreaListData() {
        if (areaList != null) {
            areaListView.setAdapter(new SimpleAdapter(this, areaList,
                    R.layout.area_item, new String[] {
                            "areaName"
                    },
                    new int[] {
                            R.id.tv_area_item_name
                    }));
        }
        areaListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int parameInt, long arg3) {
                HashMap<String, Object> areaMap = areaList.get(parameInt);
                areaId = (String) areaMap.get("areaId");
                conAreaLayout.setBackgroundColor(getResources().getColor(
                        R.color.transparent));
                if (areaFilterLayout.getVisibility() == 8) {
                    showFilter(areaFilterLayout);
                } else {
                    hideFilter(areaFilterLayout);
                }
                areaTv.setText(String.valueOf(areaMap.get("areaName")));
                vipListView.referesh();
            }
        });
    }

    /**
     * TODO 获取附近列表数据
     */
    private void requestVipListData(final boolean isRefresh) {

        AsyncLoadData ald = new AsyncLoadData(this, "", new AsyncAction() {

            @Override
            public void doLoad() throws Exception {
                // 获取提交参数
                Map<String, Object> nearbyVipParamMap = new HashMap<String, Object>();
                nearbyVipParamMap.put("parClass", parentClassName);
                nearbyVipParamMap.put("chiClass", childClassName);
                if (commonLocation != null) {
                    nearbyVipParamMap.put("userLongitude",
                            commonLocation.getLatitude());
                    nearbyVipParamMap.put("userDimension",
                            commonLocation.getLongitude());
                }
                nearbyVipParamMap.put("city", commonNowCityName);
                nearbyVipParamMap.put("area", areaId);
                nearbyVipParamMap.put("pageCnt", nowPage);
                nearbyVipParamMap.put("pageRow", OzblipConfig.seller_pageSize);
                nearbyVipParamMap.put("sort", sortVal);
                nearbyVipParamMap.put("language", commonLanguage);
                // 发送请求
                byte[] bVipList = HttpUtil.requestByPost(
                        NearbyVipActivity.this, Constants.SELLER_VIP_LIST_API,
                        nearbyVipParamMap);
                if (bVipList != null) {
                    nbVipList = new ParseJson()
                            .parseBusinessVipListJson(bVipList);
                }
            }

            @Override
            public void loadEnd() throws Exception {
                if (nbVipList != null && nbVipList.size() == 0) {
                    vipListView.onRefreshComplete();
                    nbVipListAdapter.removeAllItem();
                    nbVipListAdapter.notifyDataSetChanged();
                    dataTipTv.setVisibility(0);
                    return;
                }
                dataTipTv.setVisibility(8);
                if (isRefresh) {
                    vipListView.onRefreshComplete();
                    nbVipListAdapter.removeAllItem();
                    vipListView.nowPage = nowPage;
                    vipListView.totalPage = totalPage;
                } else {
                    vipListView.loadComplete();
                }
                nbVipListAdapter.addItems(nbVipList);
                if (nbVipListAdapter.dataList != null) {
                    int len = nbVipListAdapter.dataList.size();
                    activityNoticeStr = new StringBuffer();
                    for (int i = 0; i < len; i++) {
                        VipEntity vip = nbVipListAdapter.dataList.get(i);
                        activityNoticeStr.append(vip.getVipContent());
                        activityNoticeStr.append("@");
                        activityNoticeStr.append(vip.getBusinessName());
                        activityNoticeStr.append(",");
                    }
                }
                nbVipListAdapter.notifyDataSetChanged();
            }

        });
        ald.execute(0);
    }

    /**
     * 调用VIP列表适配器
     */
    public void setVipListAdapter() {
        if (CollectionUtil.UnNullAndZero(nbVipList)) {
            this.nbVipListAdapter = new VipListAdapter(NearbyVipActivity.this);
            this.nbVipListAdapter.addItems(nbVipList);
            this.vipListView.setAdapter(this.nbVipListAdapter);

        }
    }
}
